package com.elinkway.infinitemovies.download;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;

import com.apkfuns.logutils.LogUtils;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.ui.activity.SettingActivity;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.nostra13.universalimageloader.utils.L;

import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class DownloadHelper {

    private static final String TAG = "DownloadHelper";
    public static boolean RESTORE_FLAG = false;
    public static int DOWNLOAD_FILEPATH_NUMBER = 0;
    public final static String REALLY_DOWNLOADPATH_FOR_SP = "really_download_path";
    public final static String ALL_EXTSDCARD_PATH = "all_sdcard_path";
    public static String REALLY_DOWNLOAD_FILEPATH = Utils.SAVE_FILE_PATH_DIRECTORY;
    public static String NEW_ADDED_SDCARDPATH = "";
    public final static String SDCARD_COUNT = "sdcard_count";

    /**
     * 获取默认的下载地址，包括SD卡选择功能
     */
    public static String getDownloadPath() {
        SharedPreferences sharePreference = MoviesApplication.getInstance().getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
        String pathItem = sharePreference.getString(SettingActivity.DOWNLOAD_PATH, "-1");
        //当用户没有使用过设置下载路径功能或者第一次使用后重启程序并在下次使用之前时直接return REALLY_DOWNLOAD_FILEPATH
        if ("-1".equals(pathItem) || RESTORE_FLAG) {
            String restorePath = REALLY_DOWNLOAD_FILEPATH;
            if (REALLY_DOWNLOAD_FILEPATH.contains("/" + Utils.getDownLoadFolder())) {
                restorePath = REALLY_DOWNLOAD_FILEPATH.replace("/" + Utils.getDownLoadFolder(), "");
            }
            if (getSdTotalSize(restorePath) > 0) {
                return REALLY_DOWNLOAD_FILEPATH;
            }
            return getDefaultDownloadPath();//kuaikan----设置sd卡，这里需要修改
        } else {
            ArrayList<String> pathList = getExternalSdPath(MoviesApplication.getInstance());
            if (isSdcardOptional()) {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    if (DOWNLOAD_FILEPATH_NUMBER == 0) {
                        REALLY_DOWNLOAD_FILEPATH = Utils.SAVE_FILE_PATH_DIRECTORY;
                    } else if (DOWNLOAD_FILEPATH_NUMBER > 0) {
                        REALLY_DOWNLOAD_FILEPATH = pathList.get(DOWNLOAD_FILEPATH_NUMBER) + "/" + Utils.getDownLoadFolder();
                    }
                } else {
                    REALLY_DOWNLOAD_FILEPATH = pathList.get(DOWNLOAD_FILEPATH_NUMBER) + "/" + Utils.getDownLoadFolder();
                }
            } else {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    REALLY_DOWNLOAD_FILEPATH = Utils.SAVE_FILE_PATH_DIRECTORY;
                } else if (pathList != null && pathList.size() > 0) {
                    REALLY_DOWNLOAD_FILEPATH = pathList.get(0) + "/" + Utils.getDownLoadFolder();
                }
            }
        }
        LogUtils.e("final下载路径 == " + REALLY_DOWNLOAD_FILEPATH);
        return REALLY_DOWNLOAD_FILEPATH;
    }

    /**
     * 获取下载的文件的路径(计算分段视频大小和删除分段视频时用到)
     *
     * @param entity
     * @param destination
     * @return
     */
    public static String getDownLoadAbsolutePath(DownloadEntity entity, String destination) {
        if (destination == null) {
            destination = getDownloadPath();
        }
        String displayName = getSaveName(entity);
        if (DownloadInfo.MP4.equals(entity.getDownloadType())) {
            File file = new File(destination, displayName + ".mp4");
            if (entity.getDownloadUrl() == null || file.exists()) {
                return destination + "/" + displayName + ".mp4";
            }
            return destination + "/" + entity.getSaveName();
        } else if (DownloadInfo.M3U8.equals(entity.getDownloadType())) {
            return destination + "/" + displayName;
        }
        return destination + "/" + displayName + ".mp4";
    }

    public static String getDownLoadAbsolutePath(DownloadEntity entity, String destination, String fileName) {
        if (destination == null) {
            destination = getDownloadPath();
        }
        if (DownloadInfo.MP4.equals(entity.getDownloadType())) {
            File file = new File(destination, fileName + ".mp4");
            if (entity.getDownloadUrl() == null || file.exists()) {
                return destination + "/" + fileName + ".mp4";
            }
            return destination + "/" + entity.getSaveName();
        } else if (DownloadInfo.M3U8.equals(entity.getDownloadType())) {
            return destination + "/" + fileName;
        }
        return destination + "/" + fileName + ".mp4";
    }

    /**
     * 获取下载的文件的路径
     *
     * @param entity
     * @param destination
     * @return
     */
    public static String getAbsolutePath(DownloadEntity entity, String destination) {
        if (destination == null) {
            destination = getDownloadPath();
        }
        String displayName = getSaveName(entity);
        if (DownloadInfo.MP4.equals(entity.getDownloadType())) {
            File file = new File(destination, displayName + ".mp4");
            if (entity.getDownloadUrl() == null || file.exists()) {
                return destination + "/" + displayName + ".mp4";
            }
            String[] urlArr = entity.getDownloadUrl().split("/");
            return destination + "/" + entity.getSaveName() + "/" + displayName + urlArr[urlArr.length - 1];
        } else if (DownloadInfo.M3U8.equals(entity.getDownloadType())) {
            return destination + "/" + displayName;
        }
        return destination + "/" + displayName + ".mp4";
    }

    /**
     * 返回下载文件的大小
     *
     * @return
     */
    public static long getDownloadedFileSize(DownloadEntity entity, String destination) {
        String path = getPath(entity, destination);
        File file = new File(path);
        return getDirectorySize(file);
    }

    public static String getPath(DownloadEntity entity, String destination) {
        String path = DownloadHelper.getDownLoadAbsolutePath(entity, destination);
        File file = new File(path);
        if (file.exists()) {
            return path;
        }
        return DownloadHelper.getDownLoadAbsolutePath(entity, destination,  getSaveName(entity.getSaveName()));
    }

    public static String getSaveName(String str) {
        int RADIX = 10 + 26; // 10 digits + 26 letters
        byte[] md5 = getMD5(str.getBytes());
        BigInteger bi = new BigInteger(md5).abs();
        return bi.toString(RADIX);
    }

    private static byte[] getMD5(byte[] data) {
        byte[] hash = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(data);
            hash = digest.digest();
        } catch (NoSuchAlgorithmException e) {
            L.e(e);
        }
        return hash;
    }

    public static long getDirectorySize(File file) {
        if (file.isFile()) {
            return file.length();
        }
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            long fileSize = 0;
            if (childFiles == null || childFiles.length == 0) {
                return 0;
            }
            for (int i = 0; i < childFiles.length; i++) {
                fileSize += childFiles[i].length();
            }
            return fileSize;
        }
        return 0;
    }

    //有多个sd卡时，从各个sd卡中找出已下载完成的文件
    public static File getDownloadedFile(DownloadEntity entity) {
        String path = null;
        File file = null;
        try {
            ArrayList<String> pathList = getExternalSdPath(MoviesApplication.getInstance());
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                path = DownloadHelper.getAbsolutePath(entity, Utils.SAVE_FILE_PATH_DIRECTORY);
                createFilePath(Utils.SAVE_FILE_PATH_DIRECTORY, entity);
                file = new File(path);
                if (file.exists() && file.length() > 0) {
                    return file;
                }
            }
            if (pathList != null && pathList.size() > 0) {
                for (int i = 0; i < pathList.size(); i++) {
                    path = DownloadHelper.getAbsolutePath(entity, pathList.get(i) + "/" + Utils.getDownLoadFolder());
                    createFilePath(pathList.get(i) + "/" + Utils.getDownLoadFolder(), entity);
                    file = new File(path);
                    if (file.exists() && file.length() > 0) {
                        return file;
                    }
                }
            }
            path = DownloadHelper.getAbsolutePath(entity, DownloadHelper.getDownloadPath());
            createFilePath(DownloadHelper.getDownloadPath(), entity);
            file = new File(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    private static void createFilePath(String path, DownloadEntity entity) {
        entity.setPath(path);
        File file = new File(path);
        if (!file.exists())
            file.mkdirs();
    }

    private static String getSaveName(DownloadEntity entity) {
        return entity.getSaveName();
    }

    public static String constructName(DownloadEntity entity) {
        String mediaName = entity.getMedianame();
        return StringFilter(mediaName);
    }

    //过滤特殊字符
    public static String StringFilter(String str) throws PatternSyntaxException {
        String regEx = "[`~!@#$%^&*()+=|{}':;',//[//].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    private static ArrayList<String> getExternalSdPath(Context context) {
        Context mContext = context.getApplicationContext();
        StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
        try {
            Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Object result = getVolumeList.invoke(mStorageManager);
            final int length = Array.getLength(result);
            final String[] paths = new String[length];
            ArrayList<String> extSdPaths = new ArrayList<>();
            for (int i = 0; i < length; i++) {
                Object storageVolumeElement = Array.get(result, i);
                paths[i] = (String) getPath.invoke(storageVolumeElement);
                extSdPaths.add((String) getPath.invoke(storageVolumeElement));
            }
            return extSdPaths;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static double getSdTotalSize(String sdPath) {
        double totalSize = 0;
        try {
            StatFs sf = new StatFs(sdPath);
            long blockSize = sf.getBlockSize();
            long totalBlocks = sf.getBlockCount();
            totalSize = totalBlocks * blockSize / 1024 / 1024;
        } catch (Exception e) {
            LogUtils.w(TAG, "Get StatFs error:" + e.getMessage());
        }
        return totalSize;
    }

    //获取sd卡剩余空间大小，单位为M
    public static double getSdcardStorage(String sdPath) {
        double availStorage = 0;
        if (isSdcardExist(sdPath)) {
            try {
                StatFs sf = new StatFs(sdPath);
                long blockSize = sf.getBlockSize();
                long availCount = sf.getAvailableBlocks();
                availStorage = availCount * blockSize / 1024 / 1024;
            } catch (Exception e) {
                LogUtils.w(TAG, "Get StatFs error:" + e.getMessage());
            }
        }
        return availStorage;
    }

    //获取sd卡已使用的空间大小
    public static double getSdUsedStorage(String sdPath) {
        double usedStorage = 0;
        if (isSdcardExist(sdPath)) {
            try {
                StatFs sf = new StatFs(sdPath);
                long blockSize = sf.getBlockSize();
                long totalBlocks = sf.getBlockCount();
                long availCount = sf.getAvailableBlocks();
                usedStorage = (totalBlocks - availCount) * blockSize / 1024 / 1024;
            } catch (Exception e) {
                LogUtils.w(TAG, "Get StatFs error:" + e.getMessage());
            }
        }
        return usedStorage;
    }

    //某路径的sd卡是否存在
    public static boolean isSdcardExist(String path) {
        boolean isSdcardExist = false;
        ArrayList<String> pathList = getExternalSdPath(MoviesApplication.getInstance());
        if (!TextUtils.isEmpty(path) && path.equals(Environment.getExternalStorageDirectory().getAbsolutePath())) {
            isSdcardExist = true;
        } else if (pathList != null && pathList.size() > 0) {
            for (int i = 0; i < pathList.size(); i++) {
                if (pathList.get(i).equals(path)) {
                    isSdcardExist = true;
                    break;
                }
            }
        }
        return isSdcardExist;
    }

    //是否有多个存储设备可供选择
    public static boolean isSdcardOptional() {
        boolean extSdFlag = false;
        ArrayList<String> pathList = getExternalSdPath(MoviesApplication.getInstance());
        String extPath = null;
        if (pathList != null && pathList.size() > 0) {
            for (int i = 0; i < pathList.size() - 1; i++) {
                if (getSdTotalSize(pathList.get(i)) > 0) {
                    extPath = pathList.get(i);
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
                            && getSdTotalSize(Environment.getExternalStorageDirectory().getPath()) > 0) {
                        String innerPath = Environment.getExternalStorageDirectory().getPath();
                        if (extPath.contains(innerPath) && getSdTotalSize(extPath) == getSdTotalSize(innerPath)) {
                            extSdFlag = false;
                        } else {
                            extSdFlag = true;
                            break;
                        }
                    }
                }
            }
        }
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && getSdTotalSize(Environment.getExternalStorageDirectory().getPath()) > 0) {
            if (extSdFlag) {
                return true;
            } else {
                return false;
            }
        } else if (pathList != null) {
            if (pathList.size() > 1) {
                int sdcardCount = 0;
                for (int i = 0; i < pathList.size(); i++) {
                    if (getSdTotalSize(pathList.get(i)) > 0) {
                        sdcardCount++;
                        if (sdcardCount >= 2) {
                            return true;
                        }
                    }
                }
            } else {
                return false;
            }
        }
        return false;
    }

    private static String getReallyDownloadPath() {
        SharedPreferences sharePreference = MoviesApplication.getInstance().getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
        String path = sharePreference.getString(REALLY_DOWNLOADPATH_FOR_SP, "");
        return path;
    }

    public static SpannableStringBuilder[] getShowingItems() {
        ContainSizeManager mSizeManager = new ContainSizeManager();
        SpannableStringBuilder[] paths = null;
        ArrayList<String> pathList = getExternalSdPath(MoviesApplication.getInstance());
        if (isSdcardOptional()) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                if (pathList.size() == 1) {
                    paths = new SpannableStringBuilder[2];
                    paths[0] = getSpannableStringBuilder(mSizeManager.getFreeSizeForSetting(Utils.SAVE_FILE_PATH_DIRECTORY), MoviesApplication.getInstance().getString(R.string.download_phone_path) + "\n");
                    paths[1] = getSpannableStringBuilder(mSizeManager.getFreeSizeForSetting(pathList.get(0)), MoviesApplication.getInstance().getString(R.string.download_sd_path) + "\n");
                } else if (pathList.size() > 1) {
                    ArrayList<String> tempList = new ArrayList<>();
                    for (int i = 0; i < pathList.size(); i++) {
                        if (!TextUtils.isEmpty(pathList.get(i)) && !(pathList.get(i).contains("otg"))) {
                            tempList.add(pathList.get(i));
                        }
                    }
                    paths = new SpannableStringBuilder[tempList.size()];

                    paths[0] = getSpannableStringBuilder(mSizeManager.getFreeSizeForSetting(Utils.SAVE_FILE_PATH_DIRECTORY), MoviesApplication.getInstance().getString(R.string.download_phone_path) + "\n");
                    for (int j = 1; j < tempList.size(); j++) {
                        paths[j] = getSpannableStringBuilder(mSizeManager.getFreeSizeForSetting(tempList.get(j)), MoviesApplication.getInstance().getString(R.string.download_sd_path) + j + "\n");
                    }
                }
            } else {
                paths = new SpannableStringBuilder[pathList.size()];
                for (int i = 0; i < pathList.size(); i++) {
                    paths[i] = new SpannableStringBuilder(pathList.get(i).replace("/mnt/", ""));
                }
            }
        } else {
            paths = new SpannableStringBuilder[1];
            paths[0] = getSpannableStringBuilder(mSizeManager.getFreeSizeForSetting(Utils.SAVE_FILE_PATH_DIRECTORY), MoviesApplication.getInstance().getString(R.string.download_phone_path) + "\n");
        }
        return paths;
    }

    public static List<String> getStorageList() {
        List<String> pathList = getExternalSdPath(MoviesApplication.getInstance());
        List<String> realPathList = new ArrayList<>();
        if (pathList != null) {
            for (int i = 0; i < pathList.size(); i++) {
                if (!TextUtils.isEmpty(pathList.get(i)) && !(pathList.get(i).contains("otg"))) {
                    realPathList.add(pathList.get(i));
                }
            }
        }
        return realPathList;
    }

    /**
     * 拼接SpannableStringBuilder
     * 使用SpannableStringBuilder给文字添加大小和颜色
     *
     * @author daipei
     * @since 2014年8月22日 10:53:23
     */
    private static SpannableStringBuilder getSpannableStringBuilder(String path, String stringResource) {
        SpannableString ss = new SpannableString(path);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(MoviesApplication.getInstance().getResources().getColor(R.color.color_777777));
        AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(MoviesApplication.getInstance().getResources().getDimensionPixelSize(R.dimen.font_16));
        ss.setSpan(colorSpan, 0, path.length(), 0);
        ss.setSpan(sizeSpan, 0, path.length(), 0);
        SpannableStringBuilder ssb = new SpannableStringBuilder(stringResource);
        ssb.append(ss);
        return ssb;
    }

    //恢复用户选择的下载路径数据
    public static void restoreUserDownloadPath() {
        RESTORE_FLAG = true;
        SharedPreferences sharePreference = MoviesApplication.getInstance().getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
        String downloadPathItem = sharePreference.getString(SettingActivity.DOWNLOAD_PATH, "-1");
        if (!"-1".equals(downloadPathItem)) {
            if (isSdcardOptional()) {
                int pathItem = Integer.parseInt(downloadPathItem);
                ArrayList<String> pathList = getExternalSdPath(MoviesApplication.getInstance());
                if (isSdcardOptional()) {
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        if (pathItem == 0) {
                            REALLY_DOWNLOAD_FILEPATH = Utils.SAVE_FILE_PATH_DIRECTORY;
                        } else if (pathItem > 0 && pathList.size() >= pathItem) {
                            REALLY_DOWNLOAD_FILEPATH = pathList.get(pathItem) + "/" + Utils.getDownLoadFolder();
                        } else {
                            //选择一个优先级最高的sd卡作为路径
                            REALLY_DOWNLOAD_FILEPATH = getDefaultDownloadPath();
                        }
                    } else {
                        if (pathItem >= 0 && pathList.size() > pathItem) {
                            REALLY_DOWNLOAD_FILEPATH = pathList.get(pathItem) + "/" + Utils.getDownLoadFolder();
                        } else {
                            //选择一个优先级最高的sd卡作为路径
                            REALLY_DOWNLOAD_FILEPATH = getDefaultDownloadPath();
                        }
                    }
                } else {
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        REALLY_DOWNLOAD_FILEPATH = Utils.SAVE_FILE_PATH_DIRECTORY;
                    } else if (pathList != null && pathList.size() > 0) {
                        REALLY_DOWNLOAD_FILEPATH = pathList.get(0) + "/" + Utils.getDownLoadFolder();
                    } else {
                        REALLY_DOWNLOAD_FILEPATH = Utils.SAVE_FILE_PATH_DIRECTORY;
                    }
                }
                //如果恢复的下载地址与上次选择的不一致，那么就重新选择一个优先级最高的
                if (!REALLY_DOWNLOAD_FILEPATH.equals(getReallyDownloadPath()) && !StringUtil.isEmpty(getReallyDownloadPath())) {
                    REALLY_DOWNLOAD_FILEPATH = getDefaultDownloadPath();
                }
            }
        } else {
            REALLY_DOWNLOAD_FILEPATH = getDefaultDownloadPath();
        }
    }

    public static void saveReallyDownloadPath(int pathOrder) {
        if (isSdcardOptional()) {
            ArrayList<String> pathList = getExternalSdPath(MoviesApplication.getInstance());
            SharedPreferences sharePreference = MoviesApplication.getInstance().getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
            Editor editor = sharePreference.edit();
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                if (pathOrder == 0) {
                    editor.putString(REALLY_DOWNLOADPATH_FOR_SP, Utils.SAVE_FILE_PATH_DIRECTORY);
                    editor.commit();
                } else if (pathOrder > 0) {
                    editor.putString(REALLY_DOWNLOADPATH_FOR_SP, pathList.get(pathOrder) + "/" + Utils.getDownLoadFolder());
                    editor.commit();
                }
            } else {
                editor.putString(REALLY_DOWNLOADPATH_FOR_SP, pathList.get(pathOrder) + "/" + Utils.getDownLoadFolder());
                editor.commit();
            }
        }
    }

    //只在第一次安装第一次启动app的时候初始化
    public static void initSdcardCount() {
        SharedPreferences sharePreference = MoviesApplication.getInstance().getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
        int count = sharePreference.getInt(SDCARD_COUNT, -1);
        if (-1 == count) {
            storageSdcardCount();
        }
    }

    //存储所有的外置sd卡的路径
    public static void storageAllExtSdcardPath() {
        ArrayList<String> pathList = getExternalSdPath(MoviesApplication.getInstance());
        if (pathList != null && pathList.size() > 0) {
            SharedPreferences sharePreference = MoviesApplication.getInstance().getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
            Editor editor = sharePreference.edit();
            String paths = pathList.toString().replace("[", "");
            paths = paths.replace("]", "");
            LogUtils.i("all extsd paths == " + paths);
            editor.putString(ALL_EXTSDCARD_PATH, paths);
            editor.commit();
        }
    }

    //	//获取优先级最高的sd卡的路径，外置sd卡>内置，剩余空间大>剩余空间小
    public static String getDefaultDownloadPath() {
        SharedPreferences sharePreference = MoviesApplication.getInstance().getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
        Editor editor = sharePreference.edit();
        ArrayList<String> pathList = getExternalSdPath(MoviesApplication.getInstance());
        if (isSdcardOptional()) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                if (pathList.size() == 1) {
                    editor.putString(SettingActivity.DOWNLOAD_PATH, String.valueOf(1));
                    editor.commit();
                    return pathList.get(0) + "/" + Utils.getDownLoadFolder();
                }
            }
            double biggestSize = 0;
            int biggestSizePosition = 0;
            for (int i = 0; i < pathList.size(); i++) {
                double sdSize = getSdcardStorage(pathList.get(i));
                if (sdSize >= biggestSize) {
                    biggestSize = sdSize;
                    biggestSizePosition = i;
                }
                if (pathList.size() > i + 1) {
                    for (int j = i + 1; j < pathList.size() - 1; j++) {
                        double sdSizeTemp = getSdcardStorage(pathList.get(j));
                        if (sdSizeTemp >= biggestSize) {
                            biggestSize = sdSizeTemp;
                            biggestSizePosition = j;
                        }
                    }
                }
            }
            editor.putString(SettingActivity.DOWNLOAD_PATH, String.valueOf(biggestSizePosition));
            editor.commit();
            DOWNLOAD_FILEPATH_NUMBER = biggestSizePosition;
            return pathList.get(biggestSizePosition) + "/" + Utils.getDownLoadFolder();
        } else {
            DOWNLOAD_FILEPATH_NUMBER = 0;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                editor.putString(SettingActivity.DOWNLOAD_PATH, String.valueOf(0));
                editor.commit();
                return Utils.SAVE_FILE_PATH_DIRECTORY;
            } else if (pathList != null && pathList.size() > 0) {
                editor.putString(SettingActivity.DOWNLOAD_PATH, String.valueOf(0));
                editor.commit();
                return pathList.get(0) + "/" + Utils.getDownLoadFolder();
            } else {
                return Utils.SAVE_FILE_PATH_DIRECTORY;
            }
        }
    }

    //存储sd卡的个数
    public static void storageSdcardCount() {
        NEW_ADDED_SDCARDPATH = "";
        SharedPreferences sharePreference = MoviesApplication.getInstance().getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
        Editor editor = sharePreference.edit();
        editor.putInt(SDCARD_COUNT, getSdcardCount());
        editor.commit();
    }

    //获取手机中sd卡个数
    private static int getSdcardCount() {
        int sdCount = 0;
        ArrayList<String> pathList = getExternalSdPath(MoviesApplication.getInstance());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            sdCount = 1;
            if (pathList != null && pathList.size() > 0) {
                sdCount = pathList.size() + 1;
            }
        } else {
            if (pathList != null && pathList.size() > 0) {
                sdCount = pathList.size();
            }
        }
        return sdCount;
    }

}
